package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.domain.Video;
import com.tanhua.model.vo.FollowUser;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Video video) {
        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(idWorker.getNextId("video"));
        mongoTemplate.save(video);
    }

    @Override
    public PageResult findAll(Integer page, Integer pagesize, List ids) {
        //1、查询总数
        long count = 0;
        Query query1 = new Query();
        if (!CollUtil.isEmpty(ids)) {
            count = mongoTemplate.count(query1, Video.class);
            query1.addCriteria(Criteria.where("vid").in(ids));
        }
        //2、分页查询数据列表
        query1.limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query1, Video.class);
        //3、构建返回
        return new PageResult(page, pagesize, (int) count, list);
    }

    @Override
    public void saveFollowUser(FollowUser followUser) {
        Query query = Query.query(Criteria.where("userId").is(followUser.getUserId()).and("followUserId").is(followUser.getFollowUserId()));
        boolean exists = mongoTemplate.exists(query, FollowUser.class);
        if (!exists) {
            followUser.setId(ObjectId.get());
            followUser.setCreated(System.currentTimeMillis());
            mongoTemplate.save(followUser);
        }
    }

    @Override
    public void disSaveFollowUser(Long userId, Long followUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
        mongoTemplate.remove(query, FollowUser.class);
    }

    @Override
    public List<Video> findAll(Integer page, Integer pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        //2、分页查询数据列表
        query.limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Video.class);
    }
}